import { resultSuccess, resultError } from '../utils'
import { local } from '@/utils/jcore/storage'
import { MessageBox } from 'element-ui'
import { LogOut } from '@/router/routerUtils'

let resetLogin = false

/**响应数据处理中间件 */
export const resultHandelMid = async function (ctx, next) {
  const options = ctx.req.options
  /**
   * 添加请求token
   */
  const token = {
    'X-Authorization': local.get('token') || ''
  }
  // 为请求添加统一参数
  if (options.headers) {
    options.headers = Object.assign({}, options.headers, token)
  } else {
    options.headers = token
  }

  try {
    await next()
  } catch (error) {
    console.error(error)
    let errorMessage = '服务器异常'
    if (error.message) {
      if (error.message.includes('timeout')) {
        errorMessage = '请求超时'
      } else if (error.message.includes('code 404')) {
        errorMessage = '接口地址不存在'
      }
    }
    resultError(ctx, 'error', errorMessage)
    return
  }

  const response = ctx.res
  if (response.statusCode != 200) {
    resultError(ctx, 'error', '服务器异常')
    return
  }
  if (response.data === '') {
    resultError(ctx, 'error', '服务器返回异常')
    return
  }

  const res = response.data
  const code = res.status
  // 判断 code 然后返回
  if (code === 0) {
    return resultSuccess(ctx, res.data)
  } else if (code == 10000) {
    if (resetLogin) {
      console.log('已重定向')
      return
    }
    resetLogin = true

    local.clear()
    MessageBox.confirm('登录失效请重新登录', '提示', {
      confirmButtonText: '确定',
      showCancelButton: false,
      showClose: false,
      type: 'warning',
      center: true
    }).then(() => {
      resetLogin = false
      LogOut()
    })
    return resultError(ctx, 'fail', '登录失效需重新登录')
  } else {
    let message = res.message || res.msg || '请求失败'
    return resultError(ctx, 'fail', message)
  }
}
